// ==UserScript==
// @name           bro3_put_union_text.user.js
// @namespace      http://ronf-bro3.googlecode.com/
// @include        http://*.3gokushi.jp/union/union_history.php*
// @include        http://*.1kibaku.jp/union/union_history.php*
// @description    ブラウザ三国志合成履歴テキスト生成
// @version        0.01
// ==/UserScript==
// version date       author
// ver0.01 2011.05.12 ronf 実装テスト

var VERSION_KEY = "000put";
var VERSION = "0.01";
var urlpath;
var maxpage;
var putText = "";

var l_lv_count = {}; // LV別LVUP合成成否数
var l_success_unions = 0; // LVUP合成成功数
var a_success_unions = 0; // 総付与合成成功数
var r_success_unions = 0; // 総削除合成成功数

var total_unions = 0; // 総合成数
var l_total_unions = 0; // 総LVUP合成数
var a_total_unions = 0; // 総付与合成数
var r_total_unions = 0; // 総削除合成数

var g_ex_cards = 0;
var s_ex_cards = 0;

var srup_text = "";

// 共通関数
var d = document;
var $d = function(id) { return d.getElementById(id); };
var $x = function(xp,dc) { return d.evaluate(xp, dc||d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; };
var $e = function(key) { return d.evaluate(key, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); };

//----------------//
// メインルーチン //
//----------------//
(function(){
	if (location.pathname == "/union/union_history.php") {
		// 合成履歴画面のみ動作

		//HTML追加
		addHtml();
	}
})();

//------------//
// HTMLの生成 //
//------------//
function addHtml() {

	//--------------------------------------//
	// 画面生成                             //
	//--------------------------------------//

	//----------------//
	// コンテナの取得 //
	//----------------//
	var container;
	var pager = $e('//*[@class="pager"]');
	var bbs = $e('//*[@id="gray02Wrapper"]');
	if (pager.snapshotLength == 0) {
		container = bbs.snapshotItem(0);
	} else {
		container = pager.snapshotItem(0);
	}
	

	//----------------//
	//-- ヘッダー部 --//
	//----------------//
	//-- コントロール配置DIV --//
	var linksDiv = document.createElement("div");
	container.appendChild(linksDiv);

	//-- ツール名称ラベル --//
	var textLabel = document.createElement("span");
	textLabel.id = "toolLabel";
	textLabel.style.fontSize = "16px";
	textLabel.innerHTML = "<br><b>合成履歴抽出 Ver." + VERSION + "</b>";
	textLabel.style.color = "black";
	textLabel.style.width = "725px";
	linksDiv.appendChild(textLabel);

	//-- (改行) --//
	textLabel = document.createElement("span");
	textLabel.innerHTML = "<br>";
	linksDiv.appendChild(textLabel);

	//-- ページ数表示 --//
	var ckLabel = document.createElement("span");
	ckLabel.style.fontSize = "14px";
	ckLabel.style.marginLeft = "16px";
	ckLabel.innerHTML = "履歴ページ数";
	linksDiv.appendChild(ckLabel);

	ckLabel = document.createElement("span");
	ckLabel.style.fontSize = "14px";
	ckLabel.id = "pageNo";
	ckLabel.style.marginLeft = "4px";
	ckLabel.innerHTML = "0";
	linksDiv.appendChild(ckLabel);

	ckLabel = document.createElement("span");
	ckLabel.style.fontSize = "14px";
	ckLabel.style.marginLeft = "4px";
	ckLabel.innerHTML = "/";
	linksDiv.appendChild(ckLabel);

	var data = $e('//ul[@class="pager"]/li[@class="last"]//a[@title="last page"]');
	if( data.snapshotLength > 0 ){
		var ref = data.snapshotItem(0).getAttribute("href");
		maxpage = ref.replace(/^.*\?p=/,"");
		urlpath = ref.replace(/\?p=.*$/,"");
	}
	else{
		var data = $e('//ul[@class="pager"]/li/b');
		if( data.snapshotLength > 0 ){
			maxpage = data.snapshotItem(0).textContent;

			var data = $e('//ul[@class="pager"]/li//a[@title="first page"]');
			var ref = data.snapshotItem(0).getAttribute("href");
			urlpath = ref.replace(/\?p=.*$/,"");
		}
		else{
			maxpage = 1;
		}
	}

	ckLabel = document.createElement("span");
	ckLabel.style.fontSize = "14px";
	ckLabel.id = "lastPageNo";
	ckLabel.style.marginLeft = "4px";
	ckLabel.innerHTML = maxpage;
	linksDiv.appendChild(ckLabel);

	//-- 情報取得ボタン --//
	var button1 = document.createElement("input");
	button1.type = "button";
	button1.id = "ckButton1";
	button1.style.fontSize = "12px";
	button1.style.marginLeft = "16px";
	button1.value = "合成履歴を抽出";
	button1.addEventListener("click", function() {getButtonClicked()}, true);
	linksDiv.appendChild(button1);

	//-- 結果全選択ボタン --//
	var button2 = document.createElement("input");
	button2.type = "button";
	button2.id = "ckButton2";
	button2.style.fontSize = "12px";
	button2.style.marginLeft = "16px";
	button2.value = "結果全選択";
	button2.addEventListener("click", function() {selectButtonClicked()}, true);
	linksDiv.appendChild(button2);

	//-- (改行) --//
	textLabel = document.createElement("span");
	textLabel.innerHTML = "<br>";
	linksDiv.appendChild(textLabel);

	var startDateLabel = document.createElement("span");
	startDateLabel.id = "startDateLabel";
	startDateLabel.style.fontSize = "14px";
	startDateLabel.style.marginLeft = "16px";
	startDateLabel.innerHTML = "開始日(20YY-MM-DD)";
	linksDiv.appendChild(startDateLabel);
	
	var startDate = document.createElement("input");
	startDate.type = "text";
	startDate.id = "startDate";
	startDate.style.fontSize = "12px";
	startDate.style.marginLeft = "16px";
	linksDiv.appendChild(startDate);

	var endDateLabel = document.createElement("span");
	endDateLabel.id = "endDateLabel";
	endDateLabel.style.fontSize = "14px";
	endDateLabel.style.marginLeft = "16px";
	endDateLabel.innerHTML = "終了日(20YY-MM-DD)";
	linksDiv.appendChild(endDateLabel);
	
	var endDate = document.createElement("input");
	endDate.type = "text";
	endDate.id = "endDate";
	endDate.style.fontSize = "12px";
	endDate.style.marginLeft = "16px";
	linksDiv.appendChild(endDate);

	//-- (改行) --//
	textLabel = document.createElement("span");
	textLabel.innerHTML = "<br>";
	linksDiv.appendChild(textLabel);

	// （ギャップ埋め）
	ckLabel = document.createElement("pre");
	ckLabel.style.height = "6px";
	linksDiv.appendChild(ckLabel);

	//----------------------------//
	// 検索結果のテキスト表示領域 //
	//----------------------------//
	textArea = document.createElement("div");
	textArea.innerHTML = "";
	textArea.style.fontSize = "14px";
	textArea.style.color = "black";
	textArea.style.backgroundColor = "#FFDEAD";
	textArea.style.width = "725px";
	textArea.style.height = "200px";
	textArea.style.overflow = "auto";
	textArea.style.border = "solid 2px";
	textArea.style.padding = "2px";
	textArea.style.marginTop = "-2px";
	textArea.style.textAlign = "left";
	linksDiv.appendChild(textArea);

	ckLabel = document.createElement("pre");
	ckLabel.id = "resultText";
	ckLabel.innerHTML = "";
	textArea.appendChild(ckLabel);

	//--------------------------//
	// 他ページ取得情報の設定域 //
	//--------------------------//
	var linksDiv2 = document.createElement("html");
	linksDiv2.id = "hiddenData";
	linksDiv2.style.display = "none";
	container.appendChild(linksDiv2);
}


//------------------------//
// 取得ボタン押下処理処理 //
//------------------------//
function getButtonClicked() {
	// ハッシュテーブル初期化
	l_lv_count = {}; // LV別LVUP合成成否数

	// LV別LVUP合成成否数の初期化
	l_lv_count[1] = {"success": 0, "total": 0};
	l_lv_count[2] = {"success": 0, "total": 0};
	l_lv_count[3] = {"success": 0, "total": 0};
	l_lv_count[4] = {"success": 0, "total": 0};
	l_lv_count[5] = {"success": 0, "total": 0};
	l_lv_count[6] = {"success": 0, "total": 0};
	l_lv_count[7] = {"success": 0, "total": 0};
	l_lv_count[8] = {"success": 0, "total": 0};
	l_lv_count[9] = {"success": 0, "total": 0};

	l_success_unions = 0; // LVUP合成成功数
	a_success_unions = 0; // 総付与合成成功数
	r_success_unions = 0; // 総削除合成成功数

	total_unions = 0; // 総合成数
	l_total_unions = 0; // 総LVUP合成数
	a_total_unions = 0; // 総付与合成数
	r_total_unions = 0; // 総削除合成数

	var textBox = $e('//*[@id="resultText"]');
	textBox.snapshotItem(0).innerHTML = "データ取得中・・・「終了しました」のダイアログが出るまでお待ち下さい";

	var button = $e('//*[@id="ckButton1"]');
	button.snapshotItem(0).disabled = true;
	button = $e('//*[@id="ckButton2"]');
	button.snapshotItem(0).disabled = true;

	// 見出し
	putText = "実行日時\tジャンル\t結果\tベースカード\t対象スキル\t増加スコア<br>";

	if( maxpage > 1 ){
		loadPage(1);
	}
	else{
		// 2ページ目以降
		var data = $e('//table[@class="commonTables"]//td');
		var text = "";

		var startDate;
		var endDate;
		var dateRe = /(\d{4})[-:](\d{1,2})[-:](\d{1,2})/;
		{
			var matches = $d("startDate").value.match(dateRe);
			if (matches) startDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
			matches = $d("endDate").value.match(dateRe);
			if (matches) endDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
		}

		for( var i = 0; i < data.snapshotLength/6; i++ ){
			if (startDate != undefined || endDate != undefined) {
				var matches = data.snapshotItem(i*6).textContent.match(dateRe);
				var targetDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
				
				if (startDate != undefined && targetDate < startDate) continue;
				if (endDate != undefined && targetDate > endDate) continue;
			}

			var res = "";
			for( var j = 0; j < 6; j++ ){
				res = res + data.snapshotItem(i*6+j).textContent.replace(/(?:^\s+)|(?:\s+$)/g, "");
				if( j < 5 ){
					res = res + "\t";
				}
			}
			text = text + res + "<br>";

			var type = data.snapshotItem(i*6+1).textContent.replace(/(?:^\s+)|(?:\s+$)/g, "");;
			var success = data.snapshotItem(i*6+2).textContent.indexOf("成功") >= 0;
			var lv;
			{
				var matches = data.snapshotItem(i*6+4).textContent.match(/LV(\d+)/);
				if (matches) lv = matches[1];
			}
			total_unions++;
			if (type == "LVUP合成") {
				l_total_unions++;
				l_lv_count[lv]["total"]++;
				if (success) {
					l_success_unions++;
					l_lv_count[lv]["success"]++;
				}
			} else if (type == "付与合成") {
				a_total_unions++;
				if (success) a_success_unions++;
			} else if (type == "削除合成") {
				r_total_unions++;
				if (success) r_success_unions++;
			}
		}

		var analyze = makeAnalyzeText();

		var textBox = $e('//*[@id="resultText"]');
		textBox.snapshotItem(0).innerHTML = analyze + '<BR><BR>' + putText + text;

		var button = $e('//*[@id="ckButton1"]');
		button.snapshotItem(0).disabled = false;
		button = $e('//*[@id="ckButton2"]');
		button.snapshotItem(0).disabled = false;

		alert("終了しました");
	}
}

//----------------------//
// ページのローディング //
//----------------------//
function loadPage(targetPageNo) {
	var opt = {
		method: 'get',
		url: urlpath + "?p=" + targetPageNo,
		onload: function(res) {
			addResult(targetPageNo, res);
		}
	}
	GM_xmlhttpRequest(opt); 
}

//--------------//
// 取得結果加算 //
//--------------//
function addResult(targetPageNo,res) {
	var pageNo = $e('//*[@id="pageNo"]');
	pageNo.snapshotItem(0).textContent = targetPageNo;

	var hidden = $e('//*[@id="hiddenData"]');
	hidden.snapshotItem(0).innerHTML = res.responseText;

	// 2ページ目以降
	var data = $e('//*[@id="hiddenData"]//table[@class="commonTables"]//td');
	var text = "";

	var startDate;
	var endDate;
	var dateRe = /(\d{4})[-:](\d{1,2})[-:](\d{1,2})/;
	{
		var matches = $d("startDate").value.match(dateRe);
		if (matches) startDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
		matches = $d("endDate").value.match(dateRe);
		if (matches) endDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
	}

	for( var i = 0; i < data.snapshotLength/6; i++ ){
		if (startDate != undefined || endDate != undefined) {
			var matches = data.snapshotItem(i*6).textContent.match(dateRe);
			var targetDate = parseInt(matches[1] * 10000, 10) + parseInt(matches[2] * 100, 10) + parseInt(matches[3], 10);
			
			if (startDate != undefined && targetDate < startDate) continue;
			if (endDate != undefined && targetDate > endDate) continue;
		}
		var res = "";
		for( var j = 0; j < 6; j++ ){
			res = res + data.snapshotItem(i*6+j).textContent.replace(/(?:^\s+)|(?:\s+$)/g, "");
			if( j < 5 ){
				res = res + "\t";
			}
		}
		text = text + res + "<br>";

		var type = data.snapshotItem(i*6+1).textContent.replace(/(?:^\s+)|(?:\s+$)/g, "");;
		var success = data.snapshotItem(i*6+2).textContent.indexOf("成功") >= 0;
		var lv;
		{
			var matches = data.snapshotItem(i*6+4).textContent.match(/LV(\d+)/);
			if (matches) lv = matches[1];
		}
		total_unions++;
		if (type == "LVUP合成") {
			l_total_unions++;
			l_lv_count[lv]["total"]++;
			if (success) {
				l_success_unions++;
				l_lv_count[lv]["success"]++;
			}
		} else if (type == "付与合成") {
			a_total_unions++;
			if (success) a_success_unions++;
		} else if (type == "削除合成") {
			r_total_unions++;
			if (success) r_success_unions++;
		}
	}

	if(maxpage > targetPageNo ){
		putText = putText + text;
		loadPage(parseInt(targetPageNo)+1);
	}
	else{
		var analyze = makeAnalyzeText();

		var textBox = $e('//*[@id="resultText"]');
		textBox.snapshotItem(0).innerHTML = analyze +
						    '<BR>合成履歴<BR>' +
						    '----------------------------------------------------------<BR>' +
						    putText + text;

		var button = $e('//*[@id="ckButton1"]');
		button.snapshotItem(0).disabled = false;
		button = $e('//*[@id="ckButton2"]');
		button.snapshotItem(0).disabled = false;

		alert("終了しました");
	}
}

//--------------//
// 全選択ボタン //
//-------------//
function selectButtonClicked() {
	// 構築ルート情報の選択
	var textBox = $x('//*[@id="resultText"]');

	var objs = textBox.firstChild;
	var obje = textBox.lastChild;

	var range = document.createRange();
	range.setStart(objs,0);
	range.setEnd(obje,obje.textContent.length);
	var sel = getSelection();
	sel.removeAllRanges();
	sel.addRange(range);
}


//--------------//
// 分析テキスト //
//-------------//
function makeAnalyzeText(){
	var text = "";
	text = text + "合成履歴分析結果<BR>";
	text = text + "----------------------------------------------------------<BR>";
	text = text + "【累計】<BR>";
	if( total_unions > 0 ){
		text = text + "　合成回数：" + total_unions + "回<BR>";
	}
	else{
		text = text + "　1枚も合成していません<BR>";
	}
	text = text + "----------------------------------------------------------<BR>";
	text = text + "【付与合成】<BR>";
	if( a_total_unions > 0 ){
		text = text + "　合成回数：" + a_total_unions + "回<BR>";
		text = text + "　　成功：" + formatRightNumber(a_success_unions,4) + "回\t" + calc_per(a_success_unions,a_total_unions) + "<br>";
	}
	else{
		text = text + "　1枚も合成していません<BR>";
	}
	text = text + "----------------------------------------------------------<BR>";
	text = text + "【削除合成】<BR>";
	if( r_total_unions > 0 ){
		text = text + "　合成回数：" + r_total_unions + "回<BR>";
		text = text + "　　成功：" + formatRightNumber(r_success_unions,4) + "回\t" + calc_per(r_success_unions,r_total_unions) + "<br>";
	}
	else{
		text = text + "　1枚も合成していません<BR>";
	}
	text = text + "----------------------------------------------------------<BR>";
	text = text + "【LVUP合成】<BR>";
	if( l_total_unions > 0 ){
		text = text + "　合成回数：" + l_total_unions + "回<BR>";
		text = text + "　　成功：" + formatRightNumber(l_success_unions,4) + "回\t" + calc_per(l_success_unions,l_total_unions) + "<br>";
		for (var lv in l_lv_count) {
		text = text + "　　LV" + lv + "+：" + l_lv_count[lv]["total"] + "回<BR>";
		text = text + "　　　成功：" + formatRightNumber(l_lv_count[lv]["success"],4) + "回\t" + calc_per(l_lv_count[lv]["success"],l_lv_count[lv]["total"]) + "<br>";
		}
	}
	else{
		text = text + "　1枚も合成していません<BR>";
	}
	return text;
}

// 小数桁数フォーマッタ
function fm_num(str){
	var temp;
	temp = String(str);

	if( temp.indexOf(".") < 0 ){
		temp = temp + ".00";
	}
	if( temp.indexOf(".") == 1 ){
		temp = "  " + temp;
	}
	if( temp.indexOf(".") == 2 ){
		temp = " " + temp;
	}
	if( temp.length != 6 ){
		temp = temp + "0";
	}

	return temp;
}

// カード枚数から比率を求める
function calc_per(num,base){
	return fm_num(Math.floor(num/base*10000)/100) + "%";
}

// 桁数整形
function formatRightNumber( num, length ){
	var fix = '    ';
	var str;
	var result = '';

	str = num.toString(10);
	if( str.length < length ){
		result = fix.substr(0,length - str.length) + str;
	}
	else{
		result = str;
	}

	return result;
}
